from pathlib import Path
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import re

class ProfessionalPage:
    def __init__(self, driver):
        self.driver = driver
        project_root = Path(__file__).parent.parent.parent
        index_path = (project_root / 'index.html').resolve()
        self.url = f"file://{index_path.as_posix()}"
        self.wait = WebDriverWait(driver, 10)
        self.current_category = None
        self.current_cm_type = None

    def load(self):
        try:
            self.driver.get(self.url)
            self.wait.until(lambda d: d.find_element(By.ID, "ProCategory"))
            return self
        except Exception as e:
            raise Exception(f"Page load failed: {str(e)}")
    
    def _wait_for_page_to_load(self):
        self.wait.until(
            EC.presence_of_element_located((By.XPATH, "//h1[text()='Professional Page']")),
            message="Timed out waiting for page to load"
        )
    
    def select_professional_category(self, category):
        select = Select(
            self.wait.until(
                EC.presence_of_element_located((By.ID, "ProCategory")),
                message=f"Timed out waiting for ProCategory dropdown"
            )
        )
        select.select_by_visible_text(category)
        self.current_category = category
        
        # 如果是中药师类别，等待并确保Type of Chinese Medicine Practitioner下拉框可见
        if category == "Listed or Registered Chinese Medicine Practitioner":
            self.wait.until(
                EC.visibility_of_element_located((By.ID, "ProCategoryOfCMP")),
                message="Timed out waiting for Chinese Medicine Practitioner type dropdown to become visible"
            )
        
        self._trigger_blur_event()
        return self
    
    def select_chinese_medicine_type(self, cm_type):
        if self.current_category != "Listed or Registered Chinese Medicine Practitioner":
            return self
            
        select = Select(
            self.wait.until(
                EC.element_to_be_clickable((By.ID, "ProCategoryOfCMP")),
                message="Timed out waiting for Chinese Medicine Practitioner type dropdown"
            )
        )
        select.select_by_visible_text(cm_type)
        self.current_cm_type = cm_type
        self._trigger_blur_event()
        return self
    
    def enter_registration_number(self, reg_no):
        field = self.wait.until(
            EC.element_to_be_clickable((By.ID, "RegNo")),
            message=f"Timed out waiting for RegNo field to become clickable"
        )
        field.clear()
        field.send_keys(str(reg_no))
        self._trigger_blur_event()
        return self
    
    def _trigger_blur_event(self):
        self.wait.until(
            EC.element_to_be_clickable((By.XPATH, "//h1[text()='Professional Page']"))
        ).click()
        time.sleep(0.5)
    
    def get_error_message(self):
        try:
            error_element = self.wait.until(
                EC.visibility_of_element_located((By.ID, "regNoError")),
                message="Timed out waiting for error message to appear"
            )
            return error_element.text.strip()
        except:
            return ""
    
    def has_error(self):
        try:
            return bool(self.get_error_message())
        except:
            return False
    
    def validate_registration_number(self, reg_no, cm_type=None):
        """Enhanced validation that always takes a screenshot regardless of validation result"""
        self.enter_registration_number(reg_no)
        
        if cm_type:
            self.select_chinese_medicine_type(cm_type)
        
        # 无论是否有错误都等待1秒让界面稳定
        time.sleep(1)
        
        # 获取验证结果和错误信息
        is_valid = not self.has_error()
        error_msg = self.get_error_message()
        
        # 总是截图
        screenshot = self.take_screenshot(f"{reg_no}_{'valid' if is_valid else 'invalid'}")
        
        return {
            "valid": is_valid,
            "error_message": error_msg,
            "screenshot": screenshot
    }
    
    def take_screenshot(self, name):
        from tests.conftest import SCREENSHOTS_DIR
        SCREENSHOTS_DIR.mkdir(parents=True, exist_ok=True)
        
        # 根据 current_category 决定命名
        if self.current_category == "Listed or Registered Chinese Medicine Practitioner":
            # 获取 Type of Chinese Medicine Practitioner 的实际选中值
            cmp_type_element = self.driver.find_element(By.ID, "ProCategoryOfCMP")
            selected_option = cmp_type_element.find_element(By.CSS_SELECTOR, "option:checked")
            selected_text = selected_option.text.strip()
            
            # 为选中的类型创建缩写
            if selected_text == "Listed Chinese Medicine Practitioner":
                category_short = "LCMP"
            elif selected_text == "Chinese Medicine Practitioner with Limited Registration":
                category_short = "LRCMP"
            elif selected_text == "Registered Chinese Medicine Practitioner":
                category_short = "RCMP"
            else:
                category_short = "CMP_Unknown"  # 默认值，以防没有选中任何选项
        else:
            # 为其他专业类别创建缩写
            category_short = {
                "Dentist": "RDT",
                "Doctor": "RMP",
                "Occupational Therapist": "ROT",
                "Physiotherapist": "RPT",
                "Registered Nurse": "RNU",
                "Enroled Nurse": "ENU",
                "Medical Laboratory Technologists": "RMT",
                "Optometrists": "ROP",
                "Pharmacists": "RPH",
                "Radiographers": "RRD",
                "Chiropractor": "CPR",
                "Dental Hygienists": "DHT"
            }.get(self.current_category, "REG")  # 默认使用REGULAR
        
        # screenshot_name = f"{category_short}_{name}"
        
        # path = SCREENSHOTS_DIR / f"{screenshot_name}.png"
        # self.driver.save_screenshot(str(path))
        # return str(path)
        # 移除特殊字符（保留字母数字和下划线）
        clean_name = re.sub(r'[^\w-]', '_', name)
        screenshot_name = f"{category_short}_{clean_name}.png"
        path = SCREENSHOTS_DIR / screenshot_name
        self.driver.save_screenshot(str(path))
        return str(path)